<script setup lang="ts">
import { toast } from 'sard-uniapp'
import { t } from '@/locale'
import { LoginType, useLoginForm, useLoginHandler, useVerifyCode } from '../composable/useLogin'

interface Props {
  redirectUrl?: string
}

const props = defineProps<Props>()

const { formData, validateForm } = useLoginForm()
const { doPhoneLogin } = useLoginHandler()
const { countdown, sendVerifyCode } = useVerifyCode()

async function handlePhoneLogin() {
  if (!validateForm(LoginType.PHONE)) {
    return
  }

  await doPhoneLogin(formData.phone, formData.verifyCode, props.redirectUrl)
}

async function handleSendVerifyCode() {
  await sendVerifyCode(formData.phone)
}

function handleAgreeTermsChange(value: boolean) {
  formData.agreeTerms = value
}
</script>

<template>
  <view class="phone-login">
    <view class="flex flex-col space-y-4">
      <view class="space-y-4">
        <sar-input
          v-model="formData.phone"
          type="number"
          :placeholder="$t('login.placeholder.phone')"
          class="w-full"
        />

        <view class="flex space-x-2">
          <sar-input
            v-model="formData.verifyCode"
            :placeholder="$t('login.placeholder.verify_code')"
            class="flex-1"
          />
          <sar-button
            type="default"
            :disabled="countdown > 0"
            class="h-10 w-24 text-sm"
            @click="handleSendVerifyCode"
          >
            {{ countdown > 0 ? `${countdown}s` : $t('login.send_verify_code') }}
          </sar-button>
        </view>
      </view>

      <sar-button
        type="default"
        class="h-12 w-full border-blue-500 bg-blue-500 text-white"
        @click="handlePhoneLogin"
      >
        {{ $t('login.login') }}
      </sar-button>

      <view class="flex items-center space-x-2">
        <sar-checkbox
          :model-value="formData.agreeTerms"
          @update:model-value="handleAgreeTermsChange"
        />
        <text class="text-sm text-gray-600">
          {{ $t('login.agree_terms') }}
          <text class="text-blue-500">{{ $t('login.user_agreement') }}</text>
          {{ $t('login.and') }}
          <text class="text-blue-500">{{ $t('login.privacy_policy') }}</text>
        </text>
      </view>
    </view>
  </view>
</template>

<style scoped>
</style>
